from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from app.models.cookbook import *
from mongoengine.base import BaseDocument
from app.util.result import *


# Create your views here.


def index(request):  # 定义站点首页视图函数
    return HttpResponse('test url')  # 后台管理首页


def get_all_cookbook(request):
    # 查询所有菜谱数据
    cookbook = CookBook.objects.all().order_by("-_id")
    # 转化数据列表
    cookbookList = query_set_to_list(cookbook)
    # 规范接口返回格式 即CodeModeDTO（code,message,data）
    #  :param code: int 返回码
    #  :param message: string 返回消息
    #  :param data: obj 返回的数据
    cookbookRes = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', cookbookList)
    print(cookbookRes.to_json())
    return HttpResponse(cookbookRes.to_json(), content_type='application/json,charset=utf-8')


@csrf_exempt
def get_cookbook_by_community(request):
    com_id = request.GET.get("community_id")
    print(com_id)
    if com_id is None or com_id is "":
        cookbookRes = CodeModeDTO(CodeModeDTO.PARAMETER_ERROR, '参数为空',None)
    else:
        # 根据community_id查询
        cookbook = CookBook.objects(community_id=com_id).order_by("-_id")
        # 转化数据列表
        cookbookList = query_set_to_list(cookbook)
        # 规范接口返回格式 即CodeModeDTO（code,message,data）
        #  :param code: int 返回码
        #  :param message: string 返回消息
        #  :param data: obj 返回的数据
        cookbookRes = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', cookbookList)
    return HttpResponse(cookbookRes.to_json(), content_type='application/json,charset=utf-8')


@csrf_exempt
def get_cookbook_info_by_id(request):
    id = request.GET.get("id")
    print(id)
    if id is None or id is "":
        cookbookRes = CodeModeDTO(CodeModeDTO.PARAMETER_ERROR, '参数为空', None)
    else:
        # 根据community_id查询
        cookbook = CookBook.objects(id=id).order_by("-_id")
        # 转化数据列表
        cookbookList = query_set_to_list(cookbook)
        # 规范接口返回格式 即CodeModeDTO（code,message,data）
        #  :param code: int 返回码
        #  :param message: string 返回消息
        #  :param data: obj 返回的数据
        cookbookRes = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', cookbookList)
    return HttpResponse(cookbookRes.to_json(), content_type='application/json,charset=utf-8')